'use strict';

//仅限于Header页面调用
function HeaderCtrl($location, $http, $cookies, UserService, $q) {
    this.login = function() {
        var email = $("#username").val();
        var pwd = $("#password").val();
        $http.post('/auth/local', {
            email: email,
            password: pwd
        })
        .then(res => {
            $cookies.put('token', res.data.token);
            UserService.get().then(function(res) {
                $cookies.put('email', res.email);
                $cookies.put('_id', res._id);
                $cookies.put('name', res.name);
            });
        });
        return true;
    },
    this.register = function() {
        var email = $("#username").val();
        var pwd = $("#password").val();
        $http.post('/ajax/user', {
            email: email,
            password: pwd,
            name: name,
        }, function(data) {
            $cookies.put('token', data.token);
        });
        return true;
    },
    this.logout = function() {
        $cookies.remove('token');
        $cookies.remove('email', res.email);
        $cookies.remove('_id', res._id);
        $cookies.remove('name', res.name);
        return true;
    },
    this.isLogin = function() {
        return UserService.isLogin();
    },
    this.get = function(params) {
        return $cookies.get(params);
    };


}

//公用UserService，在Control控制器调用
function UserService($http, $cookies, $q) {
    return {
        isLogin() {
            if ($cookies.get('token')) {
                return true;
            }
            else return false;
        },
        get() {
            if (!$cookies.get('token'))
                return false;
            var deferred = $q.defer();
            $http.get('/ajax/user/me?access_token=' + $cookies.get('token'))
            .success(function(data) {
                deferred.resolve(data);
            })
            .error(function(error){
                deferred.reject(error);
            });
            return deferred.promise;
        }
    }

}


function FooterCtrl($scope) {
 
}

angular.module('hzyw', ['ngCookies'])
    .factory('UserService', UserService)
    .controller('HeaderCtrl', HeaderCtrl)
    .directive('navbar', () => ({
        templateUrl: '../../templates/common/header.html',
        restrict: 'E',
        controller: 'HeaderCtrl',
        controllerAs: 'nav'
    }))
    .controller('FooterCtrl', FooterCtrl)
    .directive('footer', () => ({
        templateUrl: '../../templates/common/footer.html',
        restrict: 'E',
        controller: 'FooterCtrl',
    }));




